//
//  NewFeatureController.swift
//  Practice
//
//  Created by miaozhihui on 2016/12/21.
//  Copyright © 2016年 DeKuTree. All rights reserved.
//

import UIKit
import SnapKit
/// 可重用 CellId
private let newFeatureCellId = "newFeatureCellId"

/// 新特性图片的数量
private let newFeatureImageCount = 4

class NewFeatureController: UICollectionViewController {

    // MARK: - 构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = UIScreen.main.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .horizontal
        super.init(collectionViewLayout: layout)
        collectionView?.isPagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(NewFeatureCell.self, forCellWithReuseIdentifier: newFeatureCellId)
        
    }

    // MARK: UICollectionViewDataSource
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return newFeatureImageCount
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: newFeatureCellId, for: indexPath) as! NewFeatureCell
    
        // Configure the cell
        cell.imageIndex = indexPath.item
    
        return cell
    }
    
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        /// 根据偏移量计算页数
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        /// 判断是否是最后一页
        if page != newFeatureImageCount-1 {
            return
        }
        
        let cell = collectionView?.cellForItem(at: IndexPath(item: page, section: 0)) as! NewFeatureCell
        
        cell.showButtonAnim()
        
    }
}

// MARK: - 新特性Cell
private class NewFeatureCell:UICollectionViewCell {
    
    fileprivate var imageIndex:Int = 0 {
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex+1)")
            startButton.isHidden = true
        }
    }
    
    @objc private func clickStartButton() {
        print("点击体验按钮")
    }
    
    /// 显示按钮动画
    fileprivate func showButtonAnim() {
        startButton.isHidden = false
        startButton.transform = CGAffineTransform(scaleX: 0, y: 0)
        startButton.isUserInteractionEnabled = false
        UIView.animate(withDuration: 1.6,           // 动画时长
                       delay: 0,                    // 延时时间
                       usingSpringWithDamping: 0.6, // 弹力系数，0~1，越小越弹
                       initialSpringVelocity: 10,   // 初始速度，模拟重力加速度
                       options: [],                 // 动画选项
                       animations: {
                        self.startButton.transform = CGAffineTransform(scaleX: 1, y: 1)
        }) { (b) in
            self.startButton.isUserInteractionEnabled = true
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(iconView)
        addSubview(startButton)
        iconView.frame = bounds
        startButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(self.snp.bottom).multipliedBy(0.7)
        }
        startButton.addTarget(self, action: #selector(clickStartButton), for: .touchUpInside)
    }
    
    /// 图像控件
    private lazy var iconView:UIImageView = UIImageView()
    
    /// 开始体验按钮
    private lazy var startButton:UIButton = UIButton(title: "开始体验", color: UIColor.white, imageName: "new_feature_finish_button")
    
}
